<template>
  <div class="request-section">
    <div class="section-header">
      <h3>Request</h3>
      <div class="request-info">
        <n-tag v-if="transaction.request.tlsVersion" class="tls-version" size="small">{{ transaction.request.tlsVersion }}</n-tag>
        <n-tag class="http-version" size="small">Client: {{ transaction.request.clientHttpVersion }}</n-tag>
        <n-tag :type="getMethodType(transaction.request.method)" size="small">
          {{ transaction.request.method }}
        </n-tag>
      </div>
    </div>

    <!-- URL 显示 -->
    <div class="url-display">
      <n-text code class="url-text">{{ transaction.request.url }}</n-text>
    </div>

    <n-tabs type="line" size="small" class="detail-tabs">
      <n-tab-pane name="headers" tab="Headers">
        <div class="tab-content">
          <n-button 
            class="copy-btn" 
            size="tiny" 
            @click="copyHeaders" 
            :disabled="Object.keys(transaction.request.headers).length === 0"
            circle
            quaternary
          >
            <template #icon>
              <n-icon :component="CopyOutline" />
            </template>
          </n-button>
          <div v-if="Object.keys(transaction.request.headers).length === 0" class="no-data">
            无 Headers
          </div>
          <div v-else>
            <div v-for="[key, value] in Object.entries(transaction.request.headers)" :key="key" class="header-item">
              <strong>{{ key }}:</strong> {{ value }}
            </div>
          </div>
        </div>
      </n-tab-pane>

      <n-tab-pane name="params" tab="Params">
        <div class="tab-content">
          <n-button 
            class="copy-btn" 
            size="tiny" 
            @click="copyParams" 
            :disabled="urlParams.length === 0"
            circle
            quaternary
          >
            <template #icon>
              <n-icon :component="CopyOutline" />
            </template>
          </n-button>
          <div v-if="urlParams.length === 0" class="no-data">
            无参数
          </div>
          <div v-else>
            <div v-for="param in urlParams" :key="param.key" class="param-item">
              <strong>{{ param.key }}:</strong> {{ param.value }}
            </div>
          </div>
        </div>
      </n-tab-pane>

      <n-tab-pane name="cookies" tab="Cookies">
        <div class="tab-content">
          <n-button 
            class="copy-btn" 
            size="tiny" 
            @click="copyCookies" 
            :disabled="Object.keys(transaction.request.cookies || {}).length === 0"
            circle
            quaternary
          >
            <template #icon>
              <n-icon :component="CopyOutline" />
            </template>
          </n-button>
          <div v-if="Object.keys(transaction.request.cookies || {}).length === 0" class="no-data">
            无 Cookies
          </div>
          <div v-else>
            <div v-for="[key, value] in Object.entries(transaction.request.cookies || {})" :key="key"
              class="cookie-item">
              <strong>{{ key }}:</strong> {{ value }}
            </div>
          </div>
        </div>
      </n-tab-pane>

      <n-tab-pane name="raw" tab="Raw">
        <div class="tab-content">
          <n-button 
            class="copy-btn" 
            size="tiny" 
            @click="copyRaw"
            circle
            quaternary
          >
            <template #icon>
              <n-icon :component="CopyOutline" />
            </template>
          </n-button>
          <pre class="raw-content">{{ getRequestRaw() }}</pre>
        </div>
      </n-tab-pane>

      <n-tab-pane name="body" tab="Body">
        <div class="tab-content body-tab">
          <div v-if="!transaction.request.body" class="no-body">
            无请求体
          </div>
          <div v-else class="body-section">
            <BodyViewer :body="transaction.request.body" :headers="transaction.request.headers" />
          </div>
        </div>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useMessage } from 'naive-ui';
import CopyOutline from '@vicons/ionicons5/Copy';
import type { HttpTransaction } from '../types/index';
import BodyViewer from './BodyViewer.vue';
import { copyToClipboard, formatObjectForCopy, formatArrayForCopy } from '../utils/clipboard';

interface Props {
  transaction: HttpTransaction;
}

const props = defineProps<Props>();
const message = useMessage();

// 解析URL参数
const urlParams = computed(() => {
  if (!props.transaction?.request?.url) return [];
  
  try {
    const url = new URL(props.transaction.request.url);
    const params: Array<{ key: string; value: string }> = [];
    
    url.searchParams.forEach((value, key) => {
      params.push({ key, value });
    });
    
    return params;
  } catch (error) {
    // 如果URL格式不正确，尝试手动解析查询字符串
    const urlStr = props.transaction.request.url;
    const queryIndex = urlStr.indexOf('?');
    
    if (queryIndex === -1) return [];
    
    const queryString = urlStr.substring(queryIndex + 1);
    const params: Array<{ key: string; value: string }> = [];
    
    if (queryString) {
      const pairs = queryString.split('&');
      for (const pair of pairs) {
        const [key, value = ''] = pair.split('=');
        if (key) {
          params.push({
            key: decodeURIComponent(key),
            value: decodeURIComponent(value)
          });
        }
      }
    }
    
    return params;
  }
});

const getMethodType = (method: string) => {
  switch (method.toUpperCase()) {
    case 'GET': return 'info';
    case 'POST': return 'success';
    case 'PUT': return 'warning';
    case 'DELETE': return 'error';
    case 'PATCH': return 'warning';
    default: return 'default';
  }
};

const getRequestRaw = () => {
  const { request } = props.transaction;
  let raw = `${request.method} ${request.url} ${request.clientHttpVersion}\n`;

  // 添加请求头
  Object.entries(request.headers).forEach(([key, value]) => {
    raw += `${key}: ${value}\n`;
  });

  // 添加请求体
  if (request.body) {
    raw += `\n${request.body}`;
  }

  return raw;
};

// 复制功能
async function copyHeaders() {
  const text = formatObjectForCopy(props.transaction.request.headers);
  const success = await copyToClipboard(text);
  if (success) {
    message.success('Headers 已复制到剪贴板');
  } else {
    message.error('复制失败');
  }
}

async function copyParams() {
  const text = formatArrayForCopy(urlParams.value);
  const success = await copyToClipboard(text);
  if (success) {
    message.success('Params 已复制到剪贴板');
  } else {
    message.error('复制失败');
  }
}

async function copyCookies() {
  const text = formatObjectForCopy(props.transaction.request.cookies || {});
  const success = await copyToClipboard(text);
  if (success) {
    message.success('Cookies 已复制到剪贴板');
  } else {
    message.error('复制失败');
  }
}

async function copyRaw() {
  const text = getRequestRaw();
  const success = await copyToClipboard(text);
  if (success) {
    message.success('Raw 数据已复制到剪贴板');
  } else {
    message.error('复制失败');
  }
}
</script>

<style scoped lang="less">
.request-section {
  height: 100%;
  padding: 12px 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--border-color);
    flex-shrink: 0;
    height: 44px; /* 固定高度 */
    
    h3 {
      margin: 0;
      font-size: 14px;
      font-weight: 600;
      color: var(--text-color);
    }
    
    .request-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .http-version,
      .tls-version {
        font-size: 12px;
        color: #666;
      }
      
      .tls-version {
        background-color: #e8f5e8;
        color: #2d8659;
        border-color: #52c41a;
      }
    }
  }
  
  .url-display {
    margin-bottom: 12px;
    padding: 8px 12px;
    background: var(--bg-tertiary);
    border-radius: 4px;
    border: 1px solid var(--border-color);
    flex-shrink: 0;
    height: 44px; /* 固定高度 */
    box-sizing: border-box;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    display: flex;
    align-items: center;

    .url-text {
      white-space: nowrap;
      overflow: visible;
      
      :deep(code) {
        white-space: nowrap;
        overflow: visible;
      }
    }
  }
  
  .detail-tabs {
    flex: 1;
    min-height: 0;
    /* 计算高度: 100% - section-header(44px + 12px margin) - url-display(44px + 12px margin) */
    height: calc(100% - 112px);

    --n-tab-gap: 8px;
  }

  .tab-content {
    padding: 12px;
    height: 100%;
    overflow-y: auto;
    background: var(--bg-tertiary);
    border-radius: 4px;
    border: 1px solid var(--border-color);
    box-sizing: border-box;
    position: relative;

    .copy-btn {
      position: absolute;
      top: 8px;
      right: 8px;
      z-index: 10;
      background: var(--bg-color);
      border: 1px solid var(--border-color);
      opacity: 0.7;
      transition: all 0.2s ease;
      
      &:hover {
        opacity: 1;
        background: var(--primary-color-suppl);
        border-color: var(--primary-color);
      }
      
      &:disabled {
        opacity: 0.3;
        cursor: not-allowed;
      }
    }
    
    &.body-tab {
      padding: 0;
      
      .body-section {
        height: 100%;
        padding: 12px;
        box-sizing: border-box;
      }
    }

    .header-item,
    .param-item,
    .cookie-item {
      padding: 4px 0;
      border-bottom: 1px solid var(--border-color);
      color: var(--text-color);
      font-size: 12px;

      &:last-child {
        border-bottom: none;
      }

      strong {
        color: #1890ff;
        margin-right: 8px;
        font-weight: 600;
      }
    }

    .raw-content {
      margin: 0;
      padding: 12px;
      background: var(--bg-color);
      border-radius: 4px;
      border: 1px solid var(--border-color);
      white-space: pre-wrap;
      word-break: break-all;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      font-size: 12px;
      line-height: 1.4;
      color: var(--text-color);
      height: 100%;
      overflow-y: auto;
      box-sizing: border-box;
    }

    .no-data,
    .no-body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100px;
      color: #999;
    }
  }
}

.detail-tabs {
  :deep(.n-tabs) {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
    
    .n-tabs-nav {
      background: var(--bg-color);
      border-bottom: 1px solid var(--border-color);
      padding: 0 4px;
      min-height: 32px;
      flex-shrink: 0;
    }
    
    .n-tabs-tab {
      border-radius: 4px 4px 0 0;
      margin: 0 1px;
      font-weight: 500;
      font-size: 12px;
      padding: 6px 12px;
      color: var(--text-color);
    }
    
    .n-tabs-tab--active {
      background: var(--primary-color-suppl);
      color: var(--primary-color);
    }
  }

  :deep(.n-tabs-content) {
    flex: 1;
    overflow: hidden;
    background: var(--bg-color);
    display: flex;
    flex-direction: column;
  }

  :deep(.n-tab-pane) {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}
</style>